﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using AccessControl.Business;
using AccessControl.HardwareLibrary.FS80;
using AccessControl.Sida.FingerPrintCollector.FingerService;
using AccessControl.Sida.FingerPrintCollector.Properties;
using AccessControl.Utility.BitmapUtility;
using AccessControl.Utility.Tools;
using DevExpress.XtraEditors;


namespace AccessControl.Sida.FingerPrintCollector.Form
{
    public partial class IdentifyPerson : XtraForm
    {
        private bool hasScannerInstalled;

        #region Field

        private FS80Device _fs80Device;
        private readonly BitmapCreator _bitmapCreator = new BitmapCreator();
        private string _meessageParameter;
        private byte[] _fingerParameter;
        private Thread _thread;
        private string _studentCode;
        #endregion

        #region Constructor

        public IdentifyPerson()
        {
            InitializeComponent();
        }

        #endregion

        #region Event Handler

        private void IdentifyPerson_Load(object sender, EventArgs e)
        {
            try
            {
                _fs80Device = new FS80Device();
                StartThread();
                hasScannerInstalled = true;
            }
            catch (ApplicationException ex)
            {
                XtraMessageBox.Show("اسکنر اثر انگشت یافت نشد\n"+ex.Message, "سیستم کنترل تردد آریابان",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                //Close();

            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("اسکنر اثر انگشت یافت نشد\n" + ex.Message, "سیستم کنترل تردد آریابان",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                //Close();
            }
        }


        private void IdentifyPerson_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_thread!=null) _thread.Abort();
        }

        #endregion

        #region Private Method

        private static void WriteLog(String message, String callerMethod, eventLevelConstants level)
        {
            LogFile.WriteLog(LogFile.DefaultLogfileLocation + "Fingerprint Collector\\" + DateTime.Now.Date.ToString("yyyyMMdd") + " " + "IdentifyPerson " + callerMethod + ".txt", level, message);
        }

        private void StartThread()
        {
            _thread = new Thread(GetSinglePictureBoxFingerPrint);

            _thread.Start();
        }

        private void GetSinglePictureBoxFingerPrint()
        {
            try
            {
                var finger = GetSingleFingerPrint();
                _fingerParameter = finger;
                Invoke(new EventHandler(SetPictureBoxImage));
                Thread.Sleep(500);
                var errorFinger = String.Empty;

                try
                {

                    var fingerPrintEngineServerClient = new FingerPrintEngineServerClient("TcpBinding");
                    fingerPrintEngineServerClient.ClientCredentials.Windows.ClientCredential.Domain = Settings.Default.Domain;
                    fingerPrintEngineServerClient.ClientCredentials.Windows.ClientCredential.UserName = Settings.Default.Username;
                    fingerPrintEngineServerClient.ClientCredentials.Windows.ClientCredential.Password = Settings.Default.Password;

                    fingerPrintEngineServerClient.Open();
                    _studentCode = fingerPrintEngineServerClient.IdentifyPerson(out errorFinger, _fingerParameter);
                    fingerPrintEngineServerClient.Close();
                    Invoke(new EventHandler(SetStudentInfo));

                }
                catch (Exception ex)
                {
                    WriteLog(errorFinger, "GetSinglePictureBoxFingerPrint", eventLevelConstants.Warning);
                    WriteLog(ex.Message, "SubmitFingerprint", eventLevelConstants.Error);

                }

            }
            catch (Exception ex)
            {
                WriteLog(ex.Message, "GetSinglePictureBoxFingerPrint", eventLevelConstants.Error);
            }

        }

        private byte[] GetSingleFingerPrint()
        {
            try
            {
                string result;
                byte[] frame;
                do
                {
                    result = _fs80Device.ReadFinger(out frame);
                    _meessageParameter = result;
                    Invoke(new EventHandler(SetMessage));
                } while (result != String.Empty);
                return frame;
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message, "GetSingleFingerPrint", eventLevelConstants.Error);
            }
            return null;
        }

        private void SetPictureBoxImage(object Sender, EventArgs e)
        {
            pictureBoxFinger11.Image = CreatefingerPrintPicture(_fingerParameter, pictureBoxFinger11.CreateGraphics());
        }

        private void SetMessage(object sender, EventArgs e)
        {
            labelMessage.Text = _meessageParameter;
        }

        private void SetStudentInfo(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(_studentCode))
            {
                labelStudendInfo.Text = @"اثر انگشت منطبق یافت نشد";

            }
            else
            {
                var studentRow =
                    PersonBusiness.SelectByFilter(String.Format("pkPerson='{0}'", _studentCode)).Single();
                labelStudendInfo.Text = String.Format("{0} {1} {2}", studentRow.PersonFirstName, studentRow.PersonLastName, studentRow.PersonRefNumber);
            }
            if (_fs80Device != null) StartThread();
        }

        private Bitmap CreatefingerPrintPicture(byte[] frame, Graphics graphics)
        {
            try
            {
                if (frame != null && frame.Length != 0)
                {
                    var size = _fs80Device.ImageSize;
                    var hBitmap = _bitmapCreator.CreateBitmap(graphics.GetHdc(), size, frame);
                    hBitmap.RotateFlip(RotateFlipType.Rotate180FlipX);
                    return hBitmap;
                }
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message, "CreatefingerPrintPicture", eventLevelConstants.Error);
            }
            return null;
        }

        #endregion

        private void pictureBoxFinger11_Click(object sender, EventArgs e)
        {

            openFileDialog.ShowDialog();
            try
            {




                pictureBoxFinger11.Image = Image.FromFile(openFileDialog.FileName);

                var img = Image.FromFile(openFileDialog.FileName);
                var bitmap = new Bitmap(img);

                if (false)
                {
                    var ms = new MemoryStream();
                    bitmap.Save(ms, ImageFormat.Bmp);
                    _fingerParameter = ms.ToArray();
                }
                else
                {
                    var bitArr = new byte[bitmap.Width * bitmap.Height];
                    for (var h = 0; h < bitmap.Height; h++)
                        for (var w = 0; w < bitmap.Width; w++)
                            bitArr[h * bitmap.Width + w] = bitmap.GetPixel(w, h).R;

                    _fingerParameter = bitArr;
                }
                var errorFinger = String.Empty;


                try
                {

                    var fingerPrintEngineServerClient = new FingerPrintEngineServerClient("TcpBinding");
                    fingerPrintEngineServerClient.ClientCredentials.Windows.ClientCredential.Domain =
                        Settings.Default.Domain;
                    fingerPrintEngineServerClient.ClientCredentials.Windows.ClientCredential.UserName =
                        Settings.Default.Username;
                    fingerPrintEngineServerClient.ClientCredentials.Windows.ClientCredential.Password =
                        Settings.Default.Password;

                    fingerPrintEngineServerClient.Open();
                    _studentCode = fingerPrintEngineServerClient.IdentifyPerson(out errorFinger,
                                                                                _fingerParameter);
                    fingerPrintEngineServerClient.Close();
                    Invoke(new EventHandler(SetStudentInfo));

                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show("خطا در شناسایی اثر انگشت\n"+ex.Message, "سیستم کنترل تردد آریابان",
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //WriteLog(errorFinger, "Search For Picture", eventLevelConstants.Warning);
                    //WriteLog(ex.Message, "Search For Picture", eventLevelConstants.Error);

                }
            }
            catch (Exception)
            {

                throw;
            }

        }



    }
}